<?php
/*
 * @project CreativeFramework
 * @version <#RELEASE_VERSION#>
 * @license GNU Lesser General Public License
 * @author Jimmie Lin
 */
 
// Side note: Thanks go to a friend of mine (which isn't a programmer, but he likes Math, just like me)
// which gave me the basic concept of this i18n system. I'm far away from him now, and I feel bad.

class Language {
	public function __construct() {
		// No matter what, we have to have a base language array ready
		// because the way the system is developed it will drop loadl
		// anguage silently (like it returned void)
		require_once(PATH."lang/base.php");
		$this->BaseArray = $BaseLanguage;
	}
	
	//--------------------------------------------------------------
	
	/**
	 * loadLanguage
	 * @param int langid Language ID
	 * @return bool
	 */
	public function loadLanguage($langid) {
		global $DB;
		$langid = intval($langid);
		$q = $DB->Driver->simple_select("languages", "`id`, `key`", "`id` = {$langid}");
		if($DB->Driver->num_rows($q) > 0) {
			$a = $DB->Driver->fetch_array($q);
			if(file_exists(PATH."lang/{$a['key']}")) {
				require_once(PATH."lang/{$a['key']}");
				$this->TranslatedArray = $ChangedLanguage;
				return true;
			}
			else return false;
		}
		else {
			return false;
		}
	}
	
	//--------------------------------------------------------------
	/**
	 * getFormattedKey
	 * @param string key Language Key
	 * @param string argn Replaces %s's in language string 'key'
	 */
	public function getFormattedKey() {
		$args = func_get_args();
		if(count($args) == 1) { 
			if(isset($this->TranslatedArray[$args[0]])) {
				return $this->TranslatedArray[$args[0]];
			}
			elseif(isset($this->BaseArray[$args[0]])) {
				return $this->BaseArray[$args[0]];
			}
			else{
				return "{langdata:{$args[0]}}";
			}
		}
		else {
			$format = array_slice($args, 1);
			if(isset($this->TranslatedArray[$args[0]])) {
				$str = $this->TranslatedArray[$args[0]];
			}
			elseif(isset($this->BaseArray[$args[0]])) {
				$str = $this->BaseArray[$args[0]];
			}
			else{
				$str = false;
				return "{langdata:{$args[0]}}";
			}
			if($str !== false) {
				foreach($format as $key => $value) {
					$str = preg_replace("/%s/", $value, $str, 1);
				}
				return $str;
			}
		}
	}
}
